import Vue from "vue";
export default () => {
  Vue.directive("Int", {
    inserted: function (input) {
      input.addEventListener("keypress", function (e) {
        let charcode = typeof e.charCode === "number" ? e.charCode : e.keyCode;
        let re = /\d/;
        if (input.value.length === 0 && charcode === 48) {
          if (e.preventDefault) {
            e.preventDefault();
          } else {
            e.returnValue = false;
          }
        } else {
          if (
            !re.test(String.fromCharCode(charcode)) &&
            charcode > 9 &&
            !e.ctrlKey
          ) {
            if (e.preventDefault) {
              e.preventDefault();
            } else {
              e.returnValue = false;
            }
          }
        }
      });
      input.onblur = function (e) {
        if (input.value.length === 1) {
          input.value = input.value.replace(/[^1-9]/g, "");
        } else {
          input.value = input.value.replace(/[^\d]/g, "");
        }
        trigger(input, "input");
      };
    },
  });
};

const trigger = (el, type) => {
  const e = document.createEvent("HTMLEvents");
  e.initEvent(type, true, true);
  el.dispatchEvent(e);
};
